import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:yqys_target/gen/assets.gen.dart';
import 'package:yqys_target/utils/yq_colors.dart';
import 'package:yqys_target/utils/yq_screen_util.dart';
import 'package:yqys_target/widgets/yq_upload_images.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:math' as math;

const _kHeaderHeight = 230.0;
const _kAppBarHeight = 56.0;
const _kScrollHeadHeight = 100.0;
const _kBottomButtonHeight = 48.0;
const _kBottomSafeArea = 34.0;
const _kBottomPadding = 16.0;

class UploadCredentialPage extends StatefulWidget {
  const UploadCredentialPage({super.key});

  @override
  State<UploadCredentialPage> createState() => _UploadCredentialPageState();
}

class _UploadCredentialPageState extends State<UploadCredentialPage> {
  final ScrollController _scrollController = ScrollController();
  double _scrollOpacity = 0.0;
  bool _isDark = true;
  List<String> images = [];

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(_onScroll);
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  void _onScroll() {
    final offset = _scrollController.offset;
    final opacity =
        (math.min(1, math.max(0, offset / _kScrollHeadHeight))).toDouble();
    final isDark = offset < _kScrollHeadHeight;

    if (opacity != _scrollOpacity || isDark != _isDark) {
      setState(() {
        _scrollOpacity = opacity;
        _isDark = isDark;
      });
    }
  }

  void _handleImagePicked(ImageSource source) async {
    // TODO: 处理图片选择逻辑
  }

  void _handleImageDelete(int index) {
    setState(() {
      images.removeAt(index);
    });
  }

  @override
  Widget build(BuildContext context) {
    final backgroundColor = Color.lerp(
      Colors.transparent,
      Colors.white,
      _scrollOpacity,
    );

    final textColor = Color.lerp(
      Colors.white,
      Colors.black,
      _scrollOpacity,
    );

    return AnnotatedRegion<SystemUiOverlayStyle>(
      value: SystemUiOverlayStyle(
        statusBarColor: Colors.transparent,
        statusBarIconBrightness: _isDark ? Brightness.light : Brightness.dark,
        statusBarBrightness: _isDark ? Brightness.light : Brightness.dark,
      ),
      child: Scaffold(
        backgroundColor: Colors.grey[100],
        body: Stack(
          children: [
            const _HeaderBgImage(),
            CustomScrollView(
              controller: _scrollController,
              slivers: [
                _DetailAppBar(
                  textColor: textColor,
                  backgroundColor: backgroundColor,
                ),
                const _ScrollHeadPlaceHolder(),
                // 上传凭证区域
                SliverPadding(
                  padding: const EdgeInsets.symmetric(horizontal: 16),
                  sliver: SliverToBoxAdapter(
                    child: _UploadSection(
                      images: images,
                      onImagePicked: _handleImagePicked,
                      onImageDelete: _handleImageDelete,
                    ),
                  ),
                ),
                // 底部空白，为固定按钮留出空间
                SliverToBoxAdapter(
                  child: SizedBox(
                    height: _kBottomButtonHeight +
                        _kBottomSafeArea +
                        _kBottomPadding * 2,
                  ),
                ),
              ],
            ),
            const _SubmitButton(),
          ],
        ),
      ),
    );
  }
}

class _HeaderBgImage extends StatelessWidget {
  const _HeaderBgImage();

  @override
  Widget build(BuildContext context) {
    return Positioned(
      top: 0,
      left: 0,
      right: 0,
      child: SizedBox(
        height: _kHeaderHeight + YQScreenUtil.getStatusBarHeight(),
        child: Stack(
          clipBehavior: Clip.none,
          children: [
            // 背景图
            Positioned.fill(
              child: ClipRRect(
                borderRadius: const BorderRadius.only(
                  bottomLeft: Radius.circular(15),
                  bottomRight: Radius.circular(15),
                ),
                child: Image.asset(
                  Assets.images.organizationHeaderBg.path,
                  fit: BoxFit.cover,
                ),
              ),
            ),
            // 文案
            Positioned(
              top: YQScreenUtil.getStatusBarHeight() + _kAppBarHeight + 16,
              left: 22,
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Text(
                    '感召全员参与 转递人间大爱',
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 20,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const SizedBox(height: 13),
                  SizedBox(
                    height: 23,
                    child: AspectRatio(
                      aspectRatio: 190.0 / 20.0,
                      child: Stack(
                        children: [
                          Positioned.fill(
                            child: Image.asset(
                              Assets.images.headerFocusBg.path,
                              fit: BoxFit.fill,
                            ),
                          ),
                          const Positioned.fill(
                            child: Center(
                              child: Text(
                                '为您的爱心益事保驾护航',
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 15,
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class _DetailAppBar extends StatelessWidget {
  const _DetailAppBar({
    required this.textColor,
    required this.backgroundColor,
  });

  final Color? textColor;
  final Color? backgroundColor;

  @override
  Widget build(BuildContext context) {
    return SliverAppBar(
      pinned: true,
      elevation: 0,
      title: Text(
        "回传凭证",
        style: TextStyle(color: textColor),
      ),
      backgroundColor: backgroundColor,
      leading: IconButton(
        icon: Icon(Icons.arrow_back_ios, color: textColor),
        onPressed: () => Navigator.of(context).pop(),
      ),
    );
  }
}

class _ScrollHeadPlaceHolder extends StatelessWidget {
  const _ScrollHeadPlaceHolder();

  @override
  Widget build(BuildContext context) {
    return const SliverToBoxAdapter(
      child: SizedBox(height: _kScrollHeadHeight),
    );
  }
}

class _UploadSection extends StatelessWidget {
  final List<String> images;
  final Function(ImageSource) onImagePicked;
  final Function(int) onImageDelete;

  const _UploadSection({
    required this.images,
    required this.onImagePicked,
    required this.onImageDelete,
  });

  @override
  Widget build(BuildContext context) {
    return ClipRRect(
      borderRadius: BorderRadius.circular(10),
      child: Container(
        color: Colors.white,
        child: YQUploadImages(
          images: images,
          onDelete: onImageDelete,
          onImagePicked: onImagePicked,
          maxCount: 9,
          title: '上传凭证',
        ),
      ),
    );
  }
}

class _SubmitButton extends StatelessWidget {
  const _SubmitButton();

  @override
  Widget build(BuildContext context) {
    return Positioned(
      left: 0,
      right: 0,
      bottom: 0,
      child: Container(
        padding: EdgeInsets.only(
          left: 16,
          right: 16,
          bottom: YQScreenUtil.getBottomSafeHeight(),
        ),
        child: ElevatedButton(
          onPressed: () {
          },
          style: ElevatedButton.styleFrom(
            backgroundColor: Colors.green,
            fixedSize: const Size(double.infinity, _kBottomButtonHeight),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(24),
            ),
          ),
          child: const Text(
            '上传凭证',
            style: TextStyle(
              fontSize: 20,
              color: Colors.white,
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
      ),
    );
  }
}
